﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetCore.ORM;
using NetCore.Model;
namespace NetCore.BLL
{
    public class PageActionService : SerivceBase, IPageActionService
    {

        #region 基本方法
        /// <summary>
        /// 查询所有
        /// </summary>
        public List<PageActionEntity> GetAll()
        {
            ICriterion criter = Expression.Eq(PageActionEntity.__IsDeleted, false);
            return this.Query<PageActionEntity>(criter).ToList();

        }
        /// <summary>
        /// 获取单个实例的方法
        /// <param name="id">object类型</param>
        /// </summary>
        public PageActionEntity GetById(string id)
        {
            return this.GetById<PageActionEntity>(id);

        }

        /// <summary>
        /// 保存方法
        /// <param name="entity">对象</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Save(PageActionEntity entity, ref string strError)
        {
            
            if (string.IsNullOrWhiteSpace(entity.PageActionId))
            {
                entity.PageActionId = entity.PageId + (!string.IsNullOrWhiteSpace(entity.ActionId)? entity.ActionId : entity.ActionName);
            }
            if (IsExist(entity))
            {
                strError = "按钮已存在，请不要重复添加";
                return false;
            }
            return this.SaveOrUpdate(entity);

        }
        /// <summary>
        /// 删除方法
        /// <param name="deleteKey">主键，如果字符串请将字符串列表用单引号将字符串用上,如（'aaa','bbb'）</param>
        /// <param name="strError">错误信息</param>
        /// </summary>
        public bool Delete(string deleteKey, ref string strError)
        {
            if (!string.IsNullOrEmpty(deleteKey))
            {
                return this.Delete<PageActionEntity>(deleteKey,false);
            }
            return true;
        }
        /// <summary>
        /// 分页查询方法
        /// <param name="grid">分页查询的相关参数</param>
        /// </summary>
        public LigerGrid ForGrid(LigerGrid grid)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrEmpty(grid.keyWord))
            {
                criter = Expression.And(criter,

                           Expression.Like(new string[] {
                                PageActionEntity._PrimaryKeyName ,
                           }, grid.keyWord)
                           );
            }
            string pageId = grid.GetValue("pageId");
            if (!string.IsNullOrWhiteSpace(pageId))
            {
                criter = Expression.And(criter, Expression.Eq(PageActionEntity.__PageId, pageId));
            }
            var result = this.Query<PageActionEntity>(criter);
           
            return this.Query<PageActionEntity>(grid, criter);

        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 通过页面id获取选中的按钮
        /// </summary>
        /// <param name="pageId">页面id</param>
        /// <param name="isAll">是否返回所有</param>
        /// <returns>isAll=true返回所有的按钮 false返回页面已经选择的按钮</returns>
        public List<ActionsEntity> GetActionByPageId(string pageId,bool isAll=true)
        {
            ICriterion criterion = Expression.Eq(PageActionEntity.__PageId, pageId);
           // criterion = Expression.And(criterion,Expression.Eq(PageActionEntity.__PageId,pageId));
            string hql= @"select a.ActionId,a.ActionName,a.LocalName,cast(case when b.PageActionId<>'' then 1 else 0 end as bit) as IsChecked  from COMM_Actions as a 
                    left join COMM_PageAction as b on a.ActionId = b.ActionId  ";
            if (isAll)
            {
                hql += "{0} where a." + PageActionEntity.__IsDeleted + "=0 ";
            }
            else {
                hql += " where a." + PageActionEntity.__IsDeleted + "=0 {0} ";
            }
          return this.Query<ActionsEntity>(hql, criterion);
        }
        /// <summary>
        /// 保存页面按钮
        /// </summary>
        /// <param name="pageId"></param>
        /// <param name="actionItemKey"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool PageActionSave(string pageId, string actionItemKey,ref string strError)
        {
            if (string.IsNullOrWhiteSpace(pageId))
            {
                strError = "参数错误，无法保存";
                return false;
            }
            actionItemKey = string.IsNullOrWhiteSpace(actionItemKey) ? "" : actionItemKey;
            string[] item = actionItemKey.Split(new char[] { ';',','});
            ICriterion where = Expression.Eq(PageActionEntity.__PageId,pageId);
            where = Expression.And(where,Expression.Not( Expression.Eq(PageActionEntity.__ActionId, "")));

            List<PageActionEntity> lstAction = new List<PageActionEntity>();
            foreach (var key in item)
            {
                if (string.IsNullOrWhiteSpace(key))
                    continue;
                string[] values = key.Split('|');
                if (values.Length <= 2)
                    continue;
                lstAction.Add(new PageActionEntity {
                    PageActionId = pageId + "_" + values[0],
                    PageId = pageId,
                    ActionId = values[0],
                    LocalName= values[2],
                    ActionName= values[1]

                });
            }
            using (var tran = this.Begin())
            {
                try
                {
                    this.Delete<PageActionEntity>(where,false);
                    if (lstAction != null && lstAction.Count > 0)
                    {
                        this.BatchInsert<PageActionEntity>(lstAction, ref strError);
                    }
                    this.Commit();
                }
                catch (Exception ex)
                {
                    this.Rollback();

                    throw ex;
                }
            }
            return true;
        }

        /// <summary>
        /// 获取页面所有按钮
        /// </summary>
        /// <param name="pageId"></param>
        /// <param name="actionName"></param>
        /// <param name="localName"></param>
        /// <returns></returns>
        public List<PageActionEntity> ForGrid(string pageId,string actionName,string localName)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            if (!string.IsNullOrWhiteSpace(actionName))
            {
                criter = Expression.And(criter,Expression.Like( PageActionEntity.__ActionName ,  actionName)  );
            }
            if (!string.IsNullOrWhiteSpace(localName))
            {
                criter = Expression.And(criter, Expression.Like(PageActionEntity.__LocalName, localName));
            }
            if (!string.IsNullOrWhiteSpace(pageId))
            {
                criter = Expression.And(criter, Expression.Eq(PageActionEntity.__PageId, pageId));
            }
           // var result = this.Query<PageActionEntity>(criter);

            return this.Query<PageActionEntity>(criter);
        }

        /// <summary>
        /// 判断是否存在
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool IsExist(PageActionEntity entity)
        {
            ICriterion criter = Expression.Eq("IsDeleted", false);
            criter = Expression.And(criter, Expression.Eq(PageActionEntity.__ActionName, entity.ActionName));
            criter = Expression.And(criter, Expression.Eq(PageActionEntity.__PageId, entity.PageId));
            criter = Expression.And(criter, Expression.Not( Expression.Eq(PageActionEntity._PrimaryKeyName, entity.PageActionId)));
           
           return  this.Query<PageActionEntity>(criter).FirstOrDefault()!=null;
        }
        #endregion

    }
}